<?php
//声明一个克隆自身的接口
interface Prototype{
	public function copy();
	public function deepCopy();
}
class cat{
	public $name;
	public $age;
	function __construct($name,$age){
		$this->name = $name;
		$this->age = $age;
	}
}
class ClonePrototype implements Prototype{
	private $name;
	public $sex;
	public $obj;
	
	function __construct($sex){
		$this->sex = $sex;
	}
	
	public function getName(){
		return $this->name;
	}
	
	public function setName($name){
		$this->name = $name;
	}
	
	public function send($name){
		echo $name.'发送测试：'.$this->name;
	}
	/**
	 * 浅克隆
	 */
	public function copy(){
		return clone $this;
	}
	/**
	 * 深克隆
	 */
	public function deepCopy(){
		$obj = serialize($this);
		$clone_obj = unserialize($obj);
		return $clone_obj;
	}
}
$pro = new ClonePrototype('男');
$pro->obj = new Cat('小毛',3);
$pro1 = $pro->copy();
$pro1->setName('克隆猫');
$pro1->obj->age = 10;
$pro1->sex = "女";
var_dump($pro);
echo '<br/><br/>';
var_dump($pro1);
echo '<br/><br/><br/>deep:<br/>';


$pro = new ClonePrototype('男');
$pro->obj = new Cat('小毛',3);
$pro1 = $pro->deepCopy();
$pro1->setName('克隆猫');
$pro1->obj->age = 10;
$pro1->sex = "女";
var_dump($pro);
echo '<br/><br/>';
var_dump($pro1);


//克隆内存使用情况
$pro = new ClonePrototype(2);
$s1 = memory_get_usage();
$s_time = microtime();
for($i = 0;$i < 500000;$i++){
	$pro1 = $pro->copy();
}
$e_time = microtime();
$e1 = memory_get_usage();
echo '<br/><br/>克隆内存：'.($e1-$s1).'<br/>';
echo '克隆时间消耗：'.($e_time-$s_time).'<br/>';

$s2 = memory_get_usage();
$s_time = microtime();
for($i = 0;$i < 500000;$i++){
	$pro1 = new ClonePrototype(2);
}
$e_time = microtime();
$e2 = memory_get_usage();
echo "new对象使用后内存: ".($e2-$s2)."<br/>";
echo 'new对象时间消耗：'.($e_time-$s_time).'<br/>';
?>